//
//  IJSPhotos.m
//  IJSOCproject
//
//  Created by shange on 2017/5/23.
//  Copyright © 2017年 jinshan. All rights reserved.
//

#import "IJSPhotos.h"
#import <Photos/Photos.h>


@implementation IJSPhotos


#pragma mark 获取当前app自定义的相册
// 外部统一的接口
+ (void)imageSaveIntoAlbumFromImage:(UIImage *)image albumName:(NSString *)albumName onSaveStateChanged:(JSPhotoChangeHandler)saveStateBlock
{
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus]; //获取授权状态
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {  //判断是否授权
        if (status == PHAuthorizationStatusDenied)                          // 用户拒绝访问当前相册
        {
            if (oldStatus != PHAuthorizationStatusNotDetermined) // 提醒打开开关
            {
                saveStateBlock(JSAuthorizationStatusNotDetermined, nil);
            }
        } else if (status == PHAuthorizationStatusAuthorized) // 允许访问
        {
            [self isOverAuthorizationSaveIntoAlbumFromImage:image albumName:albumName OnSaveStateChanged:saveStateBlock];
        } else if (status == PHAuthorizationStatusRestricted) // 无法访问
        {
            saveStateBlock(JSAuthorizationStatusRestricted, nil);
        }
    }];
}
// 将照片保存到相册
+ (void)isOverAuthorizationSaveIntoAlbumFromImage:(UIImage *)image albumName:(NSString *)albumName OnSaveStateChanged:(JSPhotoChangeHandler)saveStateBlock
{
    // 获取保存相机胶卷中的图片
    PHFetchResult<PHAsset *> *createdAssets = [self createdAssetsFromImage:image onSaveStateChanged:saveStateBlock];
    if (createdAssets == nil) {
        saveStateBlock(JSCreatedAlbumFail, nil); //创建相册失败了
        return;
    }
    // 2, 拥有一个自定义相册
    PHAssetCollection *phCollections = [self createdPHAssetCollectionFromAlbumName:albumName onSaveStateChanged:saveStateBlock];
    if (phCollections == nil) //创建或者获取相册失败
    {
        saveStateBlock(JSCreatedAlbumFail, nil);
        return;
    }
    // 3,添加刚才保存的图片到自定义相册
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:phCollections];
        [request insertAssets:createdAssets atIndexes:[NSIndexSet indexSetWithIndex:0]];
    } error:&error];
    if (error) //保存图片失败
    {
        saveStateBlock(JSSaveImageFail, error);
    } else // 保存图片成功
    {
        saveStateBlock(JSSaveImageSuccess, nil);
    }
}

// 获取保存到相册中图片
+ (PHFetchResult<PHAsset *> *)createdAssetsFromImage:(UIImage *)image onSaveStateChanged:(JSPhotoChangeHandler)saveStateBlock
{
    NSError *error = nil;
    // 1,保存图片到相机胶卷
    __block NSString *assetID = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        assetID = [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
    } error:&error];
    if (error) {
        saveStateBlock(JSCreatedAlbumFail, error);
        return nil;
    }
    // 获取相片
    return [PHAsset fetchAssetsWithLocalIdentifiers:@[ assetID ] options:nil];
}

// 创建自定义相册
+ (PHAssetCollection *)createdPHAssetCollectionFromAlbumName:(NSString *)albumName onSaveStateChanged:(JSPhotoChangeHandler)saveStateBlock
{
    // 查询
    //1 查询
    /*
     PHAssetCollectionTypeAlbum      = 1,    自定义相册
     PHAssetCollectionTypeSmartAlbum = 2,   智能相册,系统自带相册
     PHAssetCollectionTypeMoment     = 3,  时间分
     */
    PHFetchResult<PHAssetCollection *> *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collections in fetchResult) {
        if ([collections.localizedTitle isEqualToString:albumName]) {
            return collections;
        }
    }
    /* 没有创建过相册 */
    //2 创建自己相册的 唯一标识,生成占位对象
    NSError *error = nil;
    __block NSString *photoID = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        photoID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    if (error) {
        saveStateBlock(JSPhotosNoNeed, error);
        return nil;
    }
    // 创建相册成功,并返回
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[ photoID ] options:nil].firstObject;
}


@end
